package com.wtx.fitness.service.impl;

import com.wtx.fitness.entity.Score;
import com.wtx.fitness.entity.SportItem;
import com.wtx.fitness.entity.Student;
import com.wtx.fitness.mapper.ScoreMapper;
import com.wtx.fitness.mapper.SportItemMapper;
import com.wtx.fitness.mapper.StudentMapper;
import com.wtx.fitness.service.StatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 统计分析服务实现类
 */
@Service
public class StatisticsServiceImpl implements StatisticsService {

  @Autowired
  private StudentMapper studentMapper;

  @Autowired
  private ScoreMapper scoreMapper;

  @Autowired
  private SportItemMapper sportItemMapper;

  @Override
  public Map<String, Object> getOverallStatistics() {
    Map<String, Object> result = new HashMap<>();

    // 检查Mapper是否成功注入
    if (studentMapper == null) {
      result.put("error", "studentMapper未成功注入");
      return result;
    }

    if (scoreMapper == null) {
      result.put("error", "scoreMapper未成功注入");
      return result;
    }

    // 获取学生总数
    int totalStudents = studentMapper.countAll();
    result.put("totalStudents", totalStudents);

    // 获取参测学生数
    int testedStudents = scoreMapper.countDistinctStudents();
    result.put("testedStudents", testedStudents);

    // 计算参测率，格式化为两位小数
    double participationRate = totalStudents > 0 ? (double) testedStudents / totalStudents * 100 : 0;
    result.put("participationRate", participationRate);

    // 获取男女生人数
    int maleCount = studentMapper.countByGender("男");
    int femaleCount = studentMapper.countByGender("女");
    result.put("maleCount", maleCount);
    result.put("femaleCount", femaleCount);

    // 计算男女生参测率
    int maleTested = scoreMapper.countDistinctStudentsByGender("男");
    int femaleTested = scoreMapper.countDistinctStudentsByGender("女");

    double maleParticipationRate = maleCount > 0 ? (double) maleTested / maleCount * 100 : 0;
    double femaleParticipationRate = femaleCount > 0 ? (double) femaleTested / femaleCount * 100 : 0;

    // 直接添加原始的百分比值，而不是格式化的字符串
    result.put("maleTested", maleTested);
    result.put("femaleTested", femaleTested);
    result.put("maleParticipationRate", maleParticipationRate);
    result.put("femaleParticipationRate", femaleParticipationRate);

    // 获取合格人数和合格率
    int passCount = scoreMapper.countPassStudents();
    double passRate = testedStudents > 0 ? (double) passCount / testedStudents * 100 : 0;
    result.put("passCount", passCount);
    result.put("passRate", passRate);

    // 获取总体合格率（所有成绩记录中合格的比例）
    double overallPassRate = scoreMapper.countOverallPassRate();
    result.put("overallPassRate", overallPassRate);

    return result;
  }

  @Override
  public Map<String, Object> getItemPassRateStatistics() {
    Map<String, Object> result = new HashMap<>();

    // 获取所有体测项目信息
    List<Map<String, Object>> items = new ArrayList<>();
    List<SportItem> sportItems = sportItemMapper.selectAll();

    for (SportItem item : sportItems) {
      Map<String, Object> itemMap = new HashMap<>();
      itemMap.put("itemId", item.getId());
      itemMap.put("itemName", item.getItemName());

      // 获取该项目参测人数
      int testedCount = scoreMapper.countByItemId(item.getId());
      itemMap.put("testedCount", testedCount);

      // 获取该项目合格人数
      int passCount = scoreMapper.countPassByItemId(item.getId());
      itemMap.put("passCount", passCount);

      // 计算合格率，格式化为两位小数
      double passRate = testedCount > 0 ? (double) passCount / testedCount * 100 : 0;
      itemMap.put("passRate", formatPercent(passRate));

      items.add(itemMap);
    }

    result.put("items", items);
    return result;
  }

  @Override
  public Map<String, Object> getGenderScoreDistribution() {
    Map<String, Object> result = new HashMap<>();

    // 获取男生成绩分布
    List<Map<String, Object>> maleDistribution = scoreMapper.selectScoreDistributionByGender("男");
    result.put("maleDistribution", maleDistribution);

    // 获取女生成绩分布
    List<Map<String, Object>> femaleDistribution = scoreMapper.selectScoreDistributionByGender("女");
    result.put("femaleDistribution", femaleDistribution);

    return result;
  }

  @Override
  public List<Map<String, Object>> getItemScoreGradeDistribution() {
    // 获取所有体测项目
    List<Map<String, Object>> items = sportItemMapper.selectAllItemsSimple();
    List<Map<String, Object>> distribution = new ArrayList<>();

    // 遍历每个项目，获取成绩数据
    for (Map<String, Object> item : items) {
      Integer itemId = (Integer) item.get("id");
      String itemName = (String) item.get("itemName");

      // 获取该项目的详细信息，包括单位和类型
      Map<String, Object> itemDetail = sportItemMapper.selectByIdAsMap(itemId);
      String unit = itemDetail.get("unit") != null ? (String) itemDetail.get("unit") : "";
      String itemType = determineItemType(itemDetail, unit);

      // 获取该项目的所有成绩
      List<Map<String, Object>> scores = scoreMapper.selectByItemIdAsMap(itemId);

      // 构建返回项目的成绩分布数据
      Map<String, Object> itemData = new HashMap<>();
      itemData.put("itemId", itemId);
      itemData.put("itemName", itemName);
      itemData.put("itemType", itemType);
      itemData.put("unit", unit);

      // 提取原始分数值用于前端展示
      List<Double> scoreValues = new ArrayList<>();
      for (Map<String, Object> score : scores) {
        if (score.get("score") != null) {
          try {
            double value = Double.parseDouble(score.get("score").toString());
            scoreValues.add(value);
          } catch (NumberFormatException e) {
            // 忽略无法解析为数字的成绩
          }
        }
      }

      itemData.put("scores", scoreValues);
      distribution.add(itemData);
    }

    return distribution;
  }

  /**
   * 根据项目信息和单位确定项目类型
   * 
   * @param itemDetail 项目详情
   * @param unit       单位
   * @return 项目类型（计时类/计数类/测量类）
   */
  private String determineItemType(Map<String, Object> itemDetail, String unit) {
    if (unit == null) {
      return "其他类";
    }

    // 根据单位划分项目类型
    if (unit.contains("秒") || unit.contains("分钟")) {
      return "计时类"; // 跑步、游泳等
    } else if (unit.contains("次") || unit.contains("个")) {
      return "计数类"; // 引体向上、仰卧起坐等
    } else if (unit.contains("米") || unit.contains("cm") || unit.contains("kg") || unit.contains("ml")) {
      return "测量类"; // 身高、体重、立定跳远等
    }

    return "其他类";
  }

  /**
   * 格式化百分比，保留两位小数
   */
  private double formatPercent(double value) {
    // 四舍五入到两位小数
    return Math.round(value * 100) / 100.0;
  }
}